package com.martini.satoken01.config;

import com.martini.satoken01.service.DefaultEmailService;
import com.martini.satoken01.service.EmailService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import java.util.Properties;

/**
 * @author martini at 2021/12/19 14:02
 */
@SpringBootConfiguration
public class MailConfiguration {

    @Value("${system.email.host}")
    private String host;

    @Value("${system.email.port}")
    private int port;

    @Value("${system.email.username}")
    private String username;

    @Value("${system.email.password}")
    private String password;

    @Value("${system.email.default-encoding}")
    private String defaultEncoding;

    @Value("${system.email.debug:false}")
    private boolean debug;

    @Bean
    @ConditionalOnMissingBean
    public JavaMailSenderImpl javaMailSender() {
        JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
        javaMailSender.setHost(this.host);
        javaMailSender.setPort(this.port);
        javaMailSender.setUsername(this.username);
        javaMailSender.setPassword(this.password);
        javaMailSender.setDefaultEncoding(this.defaultEncoding);
        Properties properties = new Properties();
        properties.setProperty("mail.debug", String.valueOf(debug));
        properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        properties.setProperty("mail.smtp.auth", "true");
        javaMailSender.setJavaMailProperties(properties);
        return javaMailSender;
    }

    @Bean
    @ConditionalOnMissingBean
    public EmailService emailService() {
        return new DefaultEmailService(javaMailSender());
    }
}
